/* eslint-disable camelcase */
import React, { useState } from 'react'
import { useHistory, useLocation } from 'react-router-dom'
import { InfiniteScroll, NavBar } from 'antd-mobile'
import { getSearchResult, claenSearchResult } from '@/store/actions/search'
import styles from './index.module.scss'

import ArticleItem from '@/pages/Home/components/ArtivleItem/ArticleItem'
import { useDispatch, useSelector } from 'react-redux'
import { RootState } from '@/types/store'

const Result = () => {
  const dispatch = useDispatch()
  const history = useHistory()
  const location = useLocation()
  // 获取通过 URL 地址传入的查询字符串参数
  const params = new URLSearchParams(location.search)
  const key = params.get('key')

  const { results, page } = useSelector(
    (state: RootState) => state.search.result
  )
  // 上拉刷新,无限加载组件
  const [hasMore, setHasmore] = useState(true)
  const loadMore = async () => {
    if (results === [] || results.length > 50) {
      setHasmore(false)
      return
    }
    const a: number = page + 1
    await dispatch(getSearchResult(key!.toString(), a || 1))
  }

  // 返回上一级页面
  const goBack = async () => {
    history.go(-1)
    await dispatch(claenSearchResult())
  }
  return (
    <div className={styles.root}>
      <NavBar onBack={() => goBack()}>搜索结果</NavBar>
      <div className="article-list">
        {results.map((it, idx) => <ArticleItem article={it} key={idx} />)}
        <InfiniteScroll loadMore={loadMore} hasMore={hasMore} />
      </div>
    </div>
  )
}

export default Result
